import router, { asyncRoutes } from './router'
import store from './store'

const whiteList = ['/login', '/404']

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const newArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}

// 路由前置导航守卫
router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.profile.id) {
        // 1. 获取用户的权限点
        const res = await store.dispatch('user/getUserProfile')
        console.log('权限点', res)
        // 2. 对权限点进行分解
        const firstRoutePerms = getFirstRoutePerms(res)
        console.log('一级路由权限', firstRoutePerms)
        const secondRoutePerms = getSecondRoutePerms(res)
        console.log('二级路由权限', secondRoutePerms)

        // 3. 根据用户权限点过滤动态路由
        let filterRoutes = []
        if (firstRoutePerms.length === 1 && firstRoutePerms[0] === '*') {
          filterRoutes = asyncRoutes
        } else {
          filterRoutes = asyncRoutes.filter(item => {
            return firstRoutePerms.includes(item.permission)
          }).map(item => {
            return {
              ...item,
              children: item.children.filter(child => {
                return secondRoutePerms.includes(child.permission)
              })
            }
          })
        }
        console.log('过滤后的路由', filterRoutes)
        // 4. 将过滤过的动态路由添加至路由表中
        filterRoutes.forEach(item => {
          router.addRoute(item)
        })
        // 5. 将过滤后的动态路由添加到vuex中
        store.commit('menu/setMenuList', filterRoutes)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

// 路由后置导航守卫
router.afterEach(() => {})
